<template>
  <SelectBlock @click="showDate = true" :text="showName || ''" />

  <van-popup v-model:show="showDate" round position="bottom" :teleport="body">
    <van-date-picker :model-value="date" @update:model-value="onDateChange" @cancel="showDate = false"
      @confirm="onConfirm" :columns-type="columnsType" :formatter="formatter" :max-date="maxDate">
    </van-date-picker>
  </van-popup>
</template>

<script setup>
import { onMounted, ref, watch, computed } from "vue";
import SelectBlock from "../basic-components/SelectBlock.vue";

/** 支持 按年、按月、按日 选择的 Picker 组件 */

// type = day 的时候，选择 year,month,day
// type = month 的时候，选择 year,month
// type = year 的时候，选择 year
const props = defineProps(["modelValue", "type"]);
const emits = defineEmits(["update:modelValue", "confirm"]);
const maxDate = ref(null);

const body = document.body;

const showDate = ref(false);
const date = ref(["", ""]);

// 获取当前日期
const today = new Date();
const currentYear = today.getFullYear();
const currentMonth = today.getMonth() + 1; // 月份从 0 开始，需要加 1
const currentDay = today.getDate();

// 初始化为前一个月
// const previousMonth = currentMonth === 1 ? 12 : currentMonth - 1;
// const previousYear = currentMonth === 1 ? currentYear - 1 : currentYear;
// const cy = previousYear + "";
// const cm = ("0" + previousMonth).slice(-2);
// const currentYm = [cy, cm];
// const showName = ref(`${cy}年${cm}月`);

// 初始化为当前月
const currentYm = [currentYear, currentMonth];
const showName = ref(`${currentYear}年${currentMonth}月`);

// 处理日期变化
const onDateChange = (newDate) => {
  if (Array.isArray(newDate)) {
    date.value = newDate;
  } else {
    console.warn("Invalid date value:", newDate);
    date.value = [];
  }
};

// 根据 type 动态计算 columns-type
const columnsType = computed(() => {
  if (props.type === "day") {
    return ["year", "month", "day"];
  } else if (props.type === "month") {
    return ["year", "month"];
  } else if (props.type === "year") {
    return ["year"];
  } else {
    return [];
  }
});

// 确认选择
const onConfirm = (value) => {
  showName.value = value.selectedOptions.map((d) => d.text).join("");
  showDate.value = false;
  const modelValue = value.selectedValues.join("-");
  console.log(date.value);
  emits("update:modelValue", modelValue);
  emits("confirm", modelValue);
};

// 格式化日期
const formatter = (type, option) => {
  if (type === "year") {
    option.text += "年";
  }
  if (type === "month") {
    option.text += "月";
  }
  if (type === "day") {
    option.text += "日";
  }
  return option;
};

// 监听外部 v-model 的变化
watch(
  () => props.modelValue,
  (newValue) => {
    if (newValue) {
      const parts = newValue.split("-");
      date.value = parts;
      showName.value = parts
        .map((part, index) => {
          if (index === 0) return `${part}年`;
          if (index === 1) return `${part}月`;
          if (index === 2) return `${part}日`;
        })
        .join("");
    }
  },
  { immediate: true } // 初始化时立即执行
);

// 监听 type 的变化
watch(
  () => props.type,
  (newType) => {
    if (!Array.isArray(date.value)) {
      date.value = []; // 确保 date.value 是数组
    }

    let modelValue;

    switch (newType) {
      case "day":
        if (date.value.length === 2) {
          // 补全为 day，默认设置为 01
          date.value.push("01");
          showName.value += "01日";
        } else if (date.value.length < 2) {
          // 如果数据不完整，重置为默认值（如上个月）
          date.value = [...currentYm, "01"];
          showName.value = `${date.value[0]}年${date.value[1]}月${date.value[2]}日`;
        }
        modelValue = date.value.join("-");
        break;

      case "month":
        if (date.value.length >= 2) {
          date.value = date.value.slice(0, 2); // 去除 day
          showName.value = `${date.value[0]}年${date.value[1]}月`;
        } else {
          date.value = [...currentYm];
          showName.value = `${date.value[0]}年${date.value[1]}月`;
        }
        modelValue = date.value.join("-");
        break;

      case "year":
        if (date.value.length >= 1) {
          date.value = [date.value[0]]; // 只保留 year
          showName.value = `${date.value[0]}年`;
        } else {
          date.value = [currentYm[0]];
          showName.value = `${currentYm[0]}年`;
        }
        modelValue = date.value.join("-");
        break;

      default:
        // 默认处理逻辑或错误提示
        console.warn("Unsupported type:", newType);
        return;
    }

    emits("update:modelValue", modelValue);
    emits("confirm", modelValue);
  }
);

onMounted(() => {
  maxDate.value = today; // 设置 maxDate 为当前日期
});
</script>

<style lang="scss" scoped></style>
